<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-20 16:13:44
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-20 21:12:52
 * @FilePath: /free-learning-front/src/views/RegisteConsultantView.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <div class="header-with-back">
          <span class="back-button" @click="handleBack">
            <i class="fas fa-arrow-left"></i>
            返回注册用户
          </span>
          <h1>注册成为咨询师</h1>
        </div>
        <p>加入我们，成为专业的心理咨询师</p>
      </div>

      <form @submit.prevent="handleSubmit" class="register-form">
        <div class="form-layout">
          <!-- 左侧头像区域 -->
          <div class="avatar-section">
            <div class="avatar-box">
              <div class="avatar-title">头像</div>
              <div class="avatar-container">
                <ImageUpload
                  v-model="formData.avatar"
                  :limit="1"
                  :style="{ width: '180px', height: '180px' }"
                  :support-file-type="['jpg', 'jpeg', 'png', 'gif', 'webp']"
                  :max-size="2"
                  @change="handleAvatarChange"
                />
              </div>
            </div>
          </div>

          <!-- 右侧表单区域 -->
          <div class="form-section">
            <div class="form-row">
              <div class="form-group">
                <label for="username">用户名</label>
                <div class="input-group">
                  <i class="fas fa-user"></i>
                  <input
                    type="text"
                    id="username"
                    v-model="formData.username"
                    placeholder="请输入用户名"
                    required
                  />
                </div>
              </div>

              <div class="form-group">
                <label for="nickname">姓名</label>
                <div class="input-group">
                  <i class="fas fa-user-circle"></i>
                  <input
                    type="text"
                    id="nickname"
                    v-model="formData.nickname"
                    placeholder="请输入姓名"
                    required
                  />
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="idCard">身份证号</label>
                <div class="input-group">
                  <i class="fas fa-id-card"></i>
                  <input
                    type="text"
                    id="idCard"
                    v-model="formData.idCard"
                    placeholder="请输入身份证号"
                    required
                    @input="handleIdCardInput"
                    :class="{ error: validationErrors.idCard }"
                  />
                </div>
                <div v-if="validationErrors.idCard" class="error-message">
                  {{ validationErrors.idCard }}
                </div>
              </div>

              <div class="form-group">
                <label for="gender">性别</label>
                <div class="gender-group">
                  <el-radio v-model="formData.gender" :value="0" required>
                    <span>保密</span>
                  </el-radio>
                  <el-radio v-model="formData.gender" :value="1" required>
                    <span>男</span>
                  </el-radio>
                  <el-radio v-model="formData.gender" :value="2" required>
                    <span>女</span>
                  </el-radio>
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="school">毕业院校</label>
                <div class="input-group">
                  <el-select
                    v-model="formData.schoolId"
                    filterable
                    placeholder="请选择毕业院校"
                    @change="handleSchoolChange"
                  >
                    <el-option
                      v-for="item in schoolOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </div>

              <div class="form-group">
                <label for="academicDegree">学历</label>
                <div class="input-group">
                  <el-select
                    v-model="formData.academicDegreeCode"
                    placeholder="请选择学历"
                  >
                    <el-option
                      v-for="item in academicDegreeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="expertiseList">擅长领域</label>
                <div class="input-group">
                  <el-select
                    v-model="formData.expertiseList"
                    multiple
                    placeholder="请选择擅长领域"
                  >
                    <el-option
                      v-for="item in expertiseFieldOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </div>

              <div class="form-group">
                <label for="mobile">手机号码</label>
                <div class="input-group">
                  <i class="fas fa-mobile-alt"></i>
                  <input
                    type="tel"
                    id="mobile"
                    v-model="formData.mobile"
                    placeholder="请输入手机号码"
                    maxlength="11"
                    required
                    @input="handleMobileInput"
                    :class="{ error: validationErrors.mobile }"
                  />
                </div>
                <div v-if="validationErrors.mobile" class="error-message">
                  {{ validationErrors.mobile }}
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="email">邮箱</label>
                <div class="input-group">
                  <i class="fas fa-envelope"></i>
                  <input
                    type="email"
                    id="email"
                    v-model="formData.email"
                    placeholder="请输入邮箱"
                    maxlength="50"
                    required
                    @input="handleEmailInput"
                    :class="{ error: validationErrors.email }"
                  />
                </div>
                <div v-if="validationErrors.email" class="error-message">
                  {{ validationErrors.email }}
                </div>
              </div>

              <div class="form-group">
                <label for="emailCode">邮箱验证码</label>
                <div class="input-group code-group">
                  <i class="fas fa-shield-alt"></i>
                  <input
                    type="text"
                    id="emailCode"
                    v-model="formData.emailCode"
                    placeholder="请输入验证码"
                    required
                  />
                  <button
                    type="button"
                    class="code-button"
                    :disabled="
                      !formData.email ||
                      !isValidEmail ||
                      countdown > 0 ||
                      emaiLoading
                    "
                    @click="handleSendCode"
                  >
                    <i v-if="emaiLoading" class="el-icon loading">
                      <svg class="circular" viewBox="25 25 50 50">
                        <circle
                          class="path"
                          cx="50"
                          cy="50"
                          r="20"
                          fill="none"
                        />
                      </svg>
                    </i>
                    <span v-else>
                      {{
                        countdown > 0 ? `${countdown}秒后重试` : "获取验证码"
                      }}
                    </span>
                  </button>
                </div>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>身份证正面照片</label>
                <ImageUpload
                  v-model="formData.idCardFrontUrl"
                  :limit="1"
                  is-water-mark
                  :support-file-type="['jpg', 'jpeg', 'png', 'webp']"
                  :max-size="5"
                />
              </div>

              <div class="form-group">
                <label>身份证背面照片</label>
                <ImageUpload
                  v-model="formData.idCardBackUrl"
                  :limit="1"
                  is-water-mark
                  :support-file-type="['jpg', 'jpeg', 'png', 'webp']"
                  :max-size="5"
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>学位证书照片</label>
                <ImageUpload
                  v-model="formData.degreeUrl"
                  :limit="1"
                  is-water-mark
                  :support-file-type="['jpg', 'jpeg', 'png', 'webp']"
                  :max-size="5"
                />
              </div>

              <div class="form-group">
                <label>其他资料</label>
                <FileUpload v-model="formData.otherUrl" />
              </div>
            </div>
          </div>
        </div>

        <div class="form-footer">
          <div class="form-group agreement-group">
            <label class="agreement">
              <div style="display: flex; align-items: center">
                <input
                  type="checkbox"
                  v-model="agreement"
                  required
                  style="margin-right: 10px"
                />
                <span>我已阅读并同意</span>
                <a href="#" class="terms-link">《用户协议》</a>
                <span>和</span>
                <a href="#" class="terms-link">《隐私政策》</a>
              </div>
            </label>
          </div>

          <button
            type="submit"
            class="register-button"
            :disabled="loading || !agreement"
          >
            <span v-if="loading" class="loading-spinner"></span>
            {{ loading ? "提交申请中..." : "提交申请" }}
          </button>

          <div class="login-link">
            已有账号？
            <a href="http://www.free-learning.icu:8080/" target="_blank"
              >立即登录</a
            >
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { requestConsultantRegister, sendVerificationCode } from "@/api/user";
import type { SingInConsultantForm } from "@/api/user";
import type { SchoolType } from "@/api/school";
import { querySchoolList } from "@/api/school";
import type { DictItem } from "@/api/dict";
import { getDictList } from "@/api/dict";
import ImageUpload from "@/components/ImageUpload.vue";
import FileUpload from "@/components/FileUpload.vue";

const router = useRouter();
const loading = ref(false);
const agreement = ref(false);
const schoolLoading = ref(false);
const schoolOptions = ref<SchoolType[]>([]);
const academicDegreeOptions = ref<DictItem[]>([]);
const expertiseFieldOptions = ref<DictItem[]>([]);

// 邮箱验证相关
const countdown = ref(0);
const emaiLoading = ref(false);
let timer: number | undefined;

// 验证邮箱格式
const isValidEmail = computed(() => {
  return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(
    formData.email || ""
  );
});

// 表单数据
const formData = reactive<SingInConsultantForm>({
  avatar: "",
  username: "",
  nickname: "",
  idCard: "",
  gender: undefined,
  schoolId: "",
  schoolName: "",
  academicDegreeCode: "",
  expertiseList: [],
  mobile: "",
  email: "",
  emailCode: "",
  idCardFrontUrl: "",
  idCardBackUrl: "",
  degreeUrl: "",
  otherUrl: [],
  isConsultant: true,
  roleIds: [13], // 咨询师角色ID
  deptId: 1,
});

// 表单验证状态
const validationErrors = reactive({
  idCard: "",
  mobile: "",
  email: "",
});

// 验证身份证号
const validateIdCard = (value: string) => {
  if (!value) {
    validationErrors.idCard = "请输入身份证号";
    return false;
  }
  if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
    validationErrors.idCard = "请输入正确的身份证号";
    return false;
  }
  validationErrors.idCard = "";
  return true;
};

// 验证手机号
const validateMobile = (value: string) => {
  if (!value) {
    validationErrors.mobile = "请输入手机号码";
    return false;
  }
  if (!/^1[3-9]\d{9}$/.test(value)) {
    validationErrors.mobile = "请输入正确的手机号码";
    return false;
  }
  validationErrors.mobile = "";
  return true;
};
// 验证邮箱
const validateEmail = (value: string) => {
  if (!value) {
    validationErrors.email = "请输入邮箱";
    return false;
  }
  if (!isValidEmail.value) {
    validationErrors.email = "请输入正确的邮箱格式";
    return false;
  }
  validationErrors.email = "";
  return true;
};

// 监听输入变化
const handleIdCardInput = () => {
  validateIdCard(formData.idCard as string);
};

const handleMobileInput = () => {
  validateMobile(formData.mobile as string);
};

const handleEmailInput = () => {
  validateEmail(formData.email as string);
};

// 获取学校列表
const getSchoolList = async () => {
  schoolLoading.value = true;
  try {
    const res = await querySchoolList();
    schoolOptions.value = res;
  } finally {
    schoolLoading.value = false;
  }
};

// 学校选择改变
const handleSchoolChange = (value: string) => {
  const school = schoolOptions.value.find((item) => item.id === value);
  if (school) {
    formData.schoolName = school.name;
  }
};

// 头像变更
const handleAvatarChange = (url: string) => {
  formData.avatar = url;
};

// 表单验证
const validateForm = () => {
  if (!formData.avatar) {
    ElMessage.warning("请上传头像");
    return false;
  }
  if (!/^[a-zA-Z0-9]+$/.test(formData.username as string)) {
    ElMessage.warning("用户名只能是字母和数字");
    return false;
  }
  if (!formData.nickname) {
    ElMessage.warning("请输入姓名");
    return false;
  }
  if (!formData.idCard) {
    ElMessage.warning("请输入身份证号");
    return false;
  }
  if (!formData.schoolId) {
    ElMessage.warning("请选择毕业院校");
    return false;
  }
  if (!formData.academicDegreeCode) {
    ElMessage.warning("请选择学历");
    return false;
  }
  if (!formData.expertiseList?.length) {
    ElMessage.warning("请选择擅长领域");
    return false;
  }
  if (!formData.mobile) {
    ElMessage.warning("请输入手机号码");
    return false;
  }
  if (!formData.email) {
    ElMessage.warning("请输入邮箱");
    return false;
  }
  if (!formData.emailCode) {
    ElMessage.warning("请输入邮箱验证码");
    return false;
  }
  if (!formData.idCardFrontUrl) {
    ElMessage.warning("请上传身份证正面照片");
    return false;
  }
  if (!formData.idCardBackUrl) {
    ElMessage.warning("请上传身份证背面照片");
    return false;
  }
  if (!formData.degreeUrl) {
    ElMessage.warning("请上传学位证书照片");
    return false;
  }
  if (!agreement.value) {
    ElMessage.warning("请阅读并同意用户协议和隐私政策");
    return false;
  }
  return true;
};

const openLoginPage = () => {
  let time = 3;
  const timer = setInterval(() => {
    ElMessage({
      dangerouslyUseHTMLString: true,
      message:
        "<span>申请提交成功，请等待审核,审核通过后会收到邮件通知,3秒后跳转至后台登录页</span>",
      grouping: true,
      type: "success",
    });
    time--;
    if (time <= 0) {
      ElMessage.closeAll();
      ElMessage({
        dangerouslyUseHTMLString: true,
        message:
          "如果还未跳转，请点击<a href='http://www.free-learning.icu:8080/' target='_blank'>立即登录</a>",
        grouping: true,
        type: "success",
      });
      clearInterval(timer);
      window.open(import.meta.env.VITE_APP_BACK_SYSTEM_URL);
    }
  }, 1000);
};
// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) return;
  try {
    loading.value = true;
    formData.expertiseCodes = expertiseFieldOptions.value
      .filter((item) => formData.expertiseList?.includes(item.value))
      .map((item) => {
        return {
          dictCode: item.value,
          name: item.label,
        };
      });
    formData.academicDegreeName = academicDegreeOptions.value.find(
      (item) => item.value === formData.academicDegreeCode
    )?.label;
    formData.otherUrl = formData.otherUrl?.map((item) => ({
      name: item.fileName,
      url: item.url,
      fileName: item.name,
    }));
    formData.status = 1;
    await requestConsultantRegister(formData);
    openLoginPage();
  } catch (error: any) {
  } finally {
    loading.value = false;
  }
};

// 获取字典数据
const loadDictData = async () => {
  try {
    const [academicDegree, expertiseField] = await Promise.all([
      getDictList("academic_degree"),
      getDictList("expertise_field"),
    ]);
    academicDegreeOptions.value = academicDegree;
    expertiseFieldOptions.value = expertiseField;
  } catch (error) {
    console.error("获取字典数据失败:", error);
  }
};

// 发送验证码
const handleSendCode = async () => {
  if (!formData.email || !isValidEmail.value) {
    ElMessage.warning("请输入正确的邮箱格式");
    return;
  }

  try {
    emaiLoading.value = true;
    const res = await sendVerificationCode(formData.email, "EMAIL");
    if (res) {
      ElMessage.success("验证码已发送，请查收邮件");
      // 开始倒计时
      countdown.value = 60;
      timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    }
  } catch (error) {
    console.error("发送验证码失败:", error);
  } finally {
    emaiLoading.value = false;
  }
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

const handleBack = () => {
  router.push("/register");
};

onMounted(async () => {
  await getSchoolList();
  await loadDictData();
});
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f2f5;
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 900px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  padding: 40px;
}

.register-header {
  text-align: center;
  margin-bottom: 40px;

  h1 {
    font-size: 28px;
    color: #1a1a1a;
    margin-bottom: 12px;
    font-weight: 600;
  }

  p {
    color: #666;
    font-size: 16px;
  }
}

.form-layout {
  display: grid;
  grid-template-columns: 250px 1fr;
  gap: 40px;
  margin-bottom: 30px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-box {
  border: 2px solid #eee;
  border-radius: 8px;
  padding: 20px;
  width: 100%;
}

.avatar-title {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
  text-align: center;
  margin-bottom: 20px;
}

.avatar-container {
  display: flex;
  justify-content: center;
}

.form-section {
  flex: 1;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 16px;

  label {
    display: block;
    margin-bottom: 8px;
    color: #1a1a1a;
    font-weight: 500;
    font-size: 14px;
  }
}

.input-group {
  position: relative;
  display: flex;
  align-items: center;

  i {
    position: absolute;
    left: 12px;
    color: #999;
    font-size: 16px;
    z-index: 1;
  }

  input {
    width: 100%;
    height: 40px;
    padding: 8px 12px 8px 36px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.3s;
    background: #f9fafb;

    &:focus {
      background: white;
      border-color: #1890ff;
      box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
      outline: none;
    }

    &.error {
      border-color: #ff4d4f;
      background-color: #fff2f0;

      &:focus {
        box-shadow: 0 0 0 3px rgba(255, 77, 79, 0.1);
      }
    }
  }
}

.gender-group {
  display: flex;
  gap: 20px;
  align-items: center;
  height: 40px;
  padding: 0 8px;
}

:deep(.el-select) {
  width: 100%;

  .el-input__wrapper {
    background: #f9fafb;
    border-radius: 8px;
    height: 40px;
    padding: 0 12px;

    &.is-focus {
      background: white;
      box-shadow: 0 0 0 1px #1890ff;
    }
  }
}

.form-footer {
  border-top: 1px solid #f0f0f0;
  padding-top: 24px;
}

.agreement-group {
  margin-bottom: 24px;
}

.agreement {
  display: flex;
  align-items: center;
  color: #666;
  cursor: pointer;
  font-size: 14px;
}

.terms-link {
  color: #1890ff;
  text-decoration: none;
  margin: 0 4px;

  &:hover {
    text-decoration: underline;
  }
}

.register-button {
  width: 100%;
  height: 44px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;

  &:hover {
    background-color: #40a9ff;
  }

  &:disabled {
    background-color: #d9d9d9;
    cursor: not-allowed;
  }
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.login-link {
  margin-top: 24px;
  text-align: center;
  color: #666;
  font-size: 14px;

  a {
    color: #1890ff;
    text-decoration: none;
    font-weight: 500;

    &:hover {
      text-decoration: underline;
    }
  }
}

@media (max-width: 768px) {
  .register-card {
    padding: 24px;
  }

  .form-layout {
    grid-template-columns: 1fr;
    gap: 30px;
  }

  .form-row {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .avatar-box {
    max-width: 250px;
    margin: 0 auto;
  }
}

.header-with-back {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 12px;

  .back-button {
    position: absolute;
    left: 0;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #666;
    font-size: 14px;
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
      color: #1890ff;
    }

    i {
      font-size: 16px;
    }
  }

  h1 {
    margin: 0;
  }
}

.code-group {
  position: relative;
}

.code-button {
  position: absolute;
  right: 1px;
  top: 1px;
  bottom: 1px;
  padding: 0 12px;
  font-size: 14px;
  background: #f0f0f0;
  border: none;
  border-radius: 0 8px 8px 0;
  color: #1890ff;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
  min-width: 100px;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover:not(:disabled) {
    background: #e6f7ff;
  }

  &:disabled {
    color: #999;
    cursor: not-allowed;
    background: #f5f5f5;
  }
}

.loading {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
}

.circular {
  width: 20px;
  height: 20px;
  animation: loading-rotate 2s linear infinite;
}

.path {
  stroke-dasharray: 90, 150;
  stroke-dashoffset: 0;
  stroke-width: 2;
  stroke: #1890ff;
  stroke-linecap: round;
  animation: loading-dash 1.5s ease-in-out infinite;
}

@keyframes loading-rotate {
  100% {
    transform: rotate(360deg);
  }
}

@keyframes loading-dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -40px;
  }
  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -120px;
  }
}

.input-group input:not(:last-child) {
  padding-right: 100px;
}

.error-message {
  font-size: 12px;
  color: #ff4d4f;
  margin-top: 4px;
  line-height: 1.5;
  min-height: 18px;
  padding-left: 36px;
}
</style>
